<template>
  <div class="user-management-container">
    <el-card shadow="hover" class="user-card">
      <template #header>
        <div class="header-container">
          <h3>用户管理</h3>
          <div class="header-actions">
            <el-button type="primary" size="small" @click="openAddUserDialog">添加用户</el-button>
          </div>
        </div>
      </template>

      <div class="filter-container">
        <el-form :inline="true" :model="filterForm">
          <el-form-item label="用户名">
            <el-input v-model="filterForm.username" placeholder="请输入用户名" clearable></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleFilter">查询</el-button>
            <el-button @click="resetFilter">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <el-table :data="userList" border stripe style="width: 100%">
        <el-table-column prop="username" label="用户名" width="150" />
        <el-table-column prop="email" label="邮箱" width="200" />
        <el-table-column prop="role" label="角色" width="100" />
        <el-table-column label="操作">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :page-size="pageSize"
          :current-page="currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        ></el-pagination>
      </div>
    </el-card>

    <!-- 添加用户对话框 -->
    <el-dialog v-model="addUserDialogVisible" title="添加用户" width="500px" append-to-body>
      <el-form :model="userForm" label-width="100px">
        <el-form-item label="用户名">
          <el-input v-model="userForm.username" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="userForm.email" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="userForm.role" placeholder="请选择角色">
            <el-option label="管理员" value="admin"></el-option>
            <el-option label="用户" value="user"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addUserDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitUserForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { getUsers, addUser, deleteUser } from '../../api/user';

export default {
  name: 'UserManagement',
  setup() {
    const filterForm = reactive({
      username: ''
    });

    const userList = ref([]);
    const total = ref(0);
    const pageSize = ref(10);
    const currentPage = ref(1);

    const addUserDialogVisible = ref(false);
    const userForm = reactive({
      username: '',
      email: '',
      role: ''
    });

    const fetchUsers = async () => {
      try {
        const response = await getUsers({
          page: currentPage.value,
          size: pageSize.value,
          username: filterForm.username
        });
        userList.value = response.data.users;
        total.value = response.data.total;
      } catch (error) {
        console.error('获取用户列表失败:', error);
      }
    };

    const handleFilter = () => {
      currentPage.value = 1;
      fetchUsers();
    };

    const resetFilter = () => {
      filterForm.username = '';
      currentPage.value = 1;
      fetchUsers();
    };

    const handleSizeChange = (size) => {
      pageSize.value = size;
      fetchUsers();
    };

    const handleCurrentChange = (page) => {
      currentPage.value = page;
      fetchUsers();
    };

    const openAddUserDialog = () => {
      addUserDialogVisible.value = true;
    };

    const submitUserForm = async () => {
      try {
        await addUser(userForm);
        ElMessage.success('用户添加成功');
        addUserDialogVisible.value = false;
        fetchUsers();
      } catch (error) {
        console.error('添加用户失败:', error);
      }
    };

    const handleDelete = async (user) => {
      try {
        await deleteUser(user.id);
        ElMessage.success('用户删除成功');
        fetchUsers();
      } catch (error) {
        console.error('删除用户失败:', error);
      }
    };

    onMounted(() => {
      fetchUsers();
    });

    return {
      filterForm,
      userList,
      total,
      pageSize,
      currentPage,
      addUserDialogVisible,
      userForm,
      handleFilter,
      resetFilter,
      handleSizeChange,
      handleCurrentChange,
      openAddUserDialog,
      submitUserForm,
      handleDelete
    };
  }
};
</script>

<style scoped>
.user-management-container {
  padding: 10px;
}

.user-card {
  width: 100%;
}

.header-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filter-container {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style>
